//正式版的K线图文ui件整理his
  Highcharts.setOptions({
        lang: {
            downloadJPEG: "下载JPGE格式",
            contextButtonTitle: "hello",
            rangeSelectorFrom: "日期:",
            rangeSelectorTo: "至",
            rangeSelectorZoom: "",
            loading: "加载中...",
            shortMonths: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
            weekdays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
        },
        global: {
            useUTC: false
        }
    });


    
 
 var myChart;    
 var myData; //获取数据
 var options; //记录配置项
 var avg_pxyAxisMin; //最小均价
 var avg_pxyAxisMax;  //最大均价
 var yesterdayPrice; //昨天收盘价
 var items; //图表数据项
// var avgItems=[]; //记录分时和5日的平均值。
 var mydate=new Date(),year=mydate.getFullYear(),month=mydate.getMonth(),day=mydate.getDate();
 
//记录分时线的停止交易时间---接口返回的不对，默认设置为当天23:59：59秒。
var closeTime=Math.round(new Date(year,month,day,23,59,59).getTime());

 var ChartTimer;// 方法---用于处理setInterval事件。
 var MA5=[],MA10=[],MA20=[];//记录均线
 var fSize='8px';  //坐标轴等的字体大小
 /*=====分时、5日数据处理---每次画图都得执行。====*/
 function doData(){
 		 var i=0;
		 for(i;i<items.length;i++){
		 		if(i==0){
		 			avg_pxyAxisMin=items[0][2];
		 			avg_pxyAxisMax=items[0][2];
		 		}else{
		 			if(items[i-1][1]-items[i][1] > 0){
		 				//变色
		 			}
		 			
		 		}
		 		//继续赋值
		 		avg_pxyAxisMin= avg_pxyAxisMin > items[i][1] ? items[i][1] : avg_pxyAxisMin;
		 		avg_pxyAxisMax= avg_pxyAxisMax > items[i][1] ? avg_pxyAxisMax : items[i][1];
		 }
 }
 /*==================================================*/
/*计算n日平均值的方法*/
var calculateMA = function(dayCount, data) {//此处data为[开盘，收盘，最低，最高]
	var result=[],sum=0;
	for(var i=0;i<data.length;i++){
		if(i<dayCount){
			sum+=data[i][4];
			result.push([data[i][0],sum/(i+1)]);			
		}else{
			sum=0;
			for(var j=0;j<dayCount;j++){
				sum+=data[i-j][4];				
			}
			result.push([data[i][0],sum/dayCount]);
		}
		
	}
//	console.log(result);
	return result;
};

/*求分时 日K的均价--划均价线用*/
var calAvg=function(myArray){
	var avgItems=[];
	for(var i=0;i<myArray.length;i++){
		avgItems.push( [myArray[i][0] , myArray[i][2] ] );
	}
	return avgItems;
}

/*=========事件监听===========*/
var timeOutEvent=0;
document.getElementById("container").addEventListener('touchstart',function(e){
//		timeOutEvent = setTimeout("",500);			
		e.preventDefault();	
});
//document.getElementById('container').addEventListener("touchmove",function(e){
//		clearTimeout(timeOutEvent);
//		timeOutEvent=0;
//});
document.getElementById("container").addEventListener("touchend",function(e){
//		clearTimeout(timeOutEvent);		
//		if(timeOutEvent!=0){ 
//			alert("你这是点击，不是长按"); 			
//		} 
//		return false;   
  myChart.tooltip.hide();  
   myChart.axes.forEach(function(item){
   	item.hideCrosshair();
   });
});
//function toolHide(){
////	timeOutEvent=0;
//	 
//}
/*============================*/

/*===图表公共部分配置======*/
function initOption(){
	options=null;
 options={
	chart: {
        	panning: true,//Panning为true可以使得图形能平移，false则关闭了图形平移的功能
            zoomType: null,
            pinchType:null,
            spacing:[0,0,5,0], //图的外边框和绘图区之间的距离，此属性后面跟着是数组，它们分别代表上，右，下，左四个方位的距离。
            renderTo:"container",
            backgroundColor:'#f5f5f5',                     
						events : {
                load : function() {
////                  var series = this.series;
//                  var loadData=function(){
////                      var x = new Date();
//                      //for (var i = series.length - 1; i >= 0; i--) {
////                      var x2=createData2(x, x, 2, 0, 1000)[0];
////                      console.log(x2);
//                      //series[i].addPoint([(new Date(2015,9,30,14,10)).getTime()+000,3000], false, false, true);
////                      series[0].addPoint(x2, false, false);
//                      //};
////                       
//						console.log("2");
//						myChart.redraw();
//                  }
//                  ChartTimer=setInterval(loadData, 1000);											
                }
            },                
            animation: false
        },
        title:{
            text:""
        },
        subtitle:{
            text:""
        },
        rangeSelector: {
            buttonTheme: {
           	 display: 'none' // 不显示按钮
		    		},
		    	selected: 0,
		    	buttons: [{
		    		type:'day',
		    		count:120,
		    		text:'日K对应的范围-10天'
		    	},
		    	{
						type: 'month',
						count: 24,
						text: '月K范围-6个月'
					}, {
						type: 'minute',
						count: 120,
						text: '1分钟K线范围-120分'
					},{
						type: 'minute',
						count: 240,
						text: '5分钟K线范围-120分'
					},{
						type: 'day',
						count: 1,
						text: '30分钟K线范围-1天'
					},{
						type: 'day',
						count: 2,
						text: '60分钟K线范围-2天'
					},{
						type: 'day',
						count: 1,
						text: '240分钟K线范围-1天'
					}],
		   		inputEnabled: false // 不显示日期输入框
        },
        credits: {
            enabled: false
        },
        legend: {
            enabled: false,
            title: { text: "红线" }
        },
        navigation: {
            enabled: false
        },
        navigator: {
            enabled:false,
//          height:20,
//          margin:
//          maskFill:'rgba(255,255,255,0)',
            outlineWidth:1,
            xAxis:{
            	labels:{
            		formatter:function(e){
            			return Highcharts.dateFormat("20%y-%m-%d %H:%M", this.value);
            		}
            	}
            }
//          outlineColor:'rgba(255,255,255,0)',
//          handles:{
//          	borderColor:'rgba(255,255,255,0)',
//          	backgroundColor:'rgba(255,255,255,0)'
//          }
        },
        plotOptions: {        	 
            line: {
                turboThreshold: Number.MAX_VALUE,
                dataGrouping: { enabled: false },
                connectNulls: true,
                color: "#5b9fe2",
                lineWidth: 1
            },
            candlestick:{//改变K线图的颜色
            	color: '#33AA11',  
              upColor: '#DD2200',  
              lineColor: '#33AA11',                 
              upLineColor: '#DD2200',
              maker:{  
                   states:{  
                       hover:{  
                           enabled:false
                       }  
                   }  
              }
            },
            series: {
            	 turboThreshold:0,
                states: {  //去掉鼠标悬浮的选中样式
                    hover: {  
                        enabled: false  
                    }  
                }
            }
        },
        scrollbar: {
            enabled: false
        },        
        tooltip: {
        	style:{
        		fontSize:fSize       	  	
        	},
        	followTouchMove:true,
           positioner: function () {
               return { x: 1, y: 2 } //左上角提示文字的位置
           },
            shared: true, //当提示框被共享时，整个绘图区都将捕捉鼠标指针的移动
            useHTML: true, //使用HTML代码渲染提示框的内容用以代替SVG。使用HTML允许高级格式化像在提示框中的表格和图像
            shadow: false, //是否启用提示框的阴影。
            borderColor: "rgba(255, 255, 255, 0)",
            backgroundColor: "rgba(255, 255, 255, 0)",
            valueDecimals: 2 //数据提示框数据值小数保留位数。默认为保留所有小数。
            //formatter:部分为定制内容。
        },
        xAxis: {
        	gridLineWidth:1,
//      	gridLineDashStyle:'dot',
        	tickLength:0,//刻度线的长度
            //定制显示部分坐标轴上的刻度线的单位间隔。当值为null时，刻度线间隔是根据近似于线性的(tickPixelInterval)计算的
//          tickInterval:60 * 1000, 
            ordinal:false,
//          startOnTick:true,
            endOntick:true     
//          min:items[0][0]
//          max:items[][0]
        }
        
};
	return options;
}

/*===公共部分配置end=======*/




window.onload=function(){
	fs(1);
	ChartTimer=setInterval(function(){fs(1)},1000*60);
}
//触发横屏竖屏事件时
window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', function() {
	setTimeout(function() {
//		myChart.resize();
	}, 100);
}, false);

//菜单按钮单机事件
$(".menu_btn").click(function(){
	$(this).addClass('active').siblings('button').removeClass('active'); //添加样式
	clearInterval(ChartTimer);	
	items=null;	
	var val=$(this).val(); 
	
	switch (val){
		case '1': 
		case '2': fs(val);ChartTimer=setInterval(function(){fs(val) },1000 * 60);  break;
		case '3': kline(val);ChartTimer=setInterval(function(){kline(val) },1000*60);break; 
		case '4':  
		case '5':  
		case '6':  
		case '7':  
		case '8': 
		case '9':  
		case '10':kline(val);  break;	
		default:
			break;
	}
});

/*==各类型的图表获取数据并执行绘制===*/
//分时图
function fs(typeVal){	
AJAX('/Quotation/GetRealTimePrice',{
	Code:GetQueryString("Code"), //产品代码
	QuotationType:typeVal //分时线类型
//	StartDate:'2016-08-31'
},function(data){	  
	    yesterdayPrice=data.entity.YesterdayPrice;
	    items=JSON.parse(data.entity.Entity).sort();
			doData();//处理数据
		
			items.push([closeTime,null]); //补空---结束时间
			initOption();
			//设置图表项
			options.tooltip.formatter=function(){
//				var e, t, o = this;
//				return $.each(this.points, function () {
//				var n = this.point.index;
//				    e = Highcharts.dateFormat("20%y-%m-%d %H:%M", this.x),
//				    t = "当前价:" + Highcharts.numberFormat(o.y,2)				   
//				}),
//				"当前时间："+e + "  " + t;
				
				var e=Highcharts.dateFormat("20%y-%m-%d %H:%M", this.points[0].x),
				    t="当前价:" + Highcharts.numberFormat(this.points[0].y,2),
				    avg="均价："+Highcharts.numberFormat(this.points[1].y,2);				    
				return e+"  "+'<span style="color:#657FFB">'+t+'</span>'+"  "+'<span style="color:orange;">'+avg+'</span>';
			};
			//设置y轴
			options.yAxis=[{
	      allowDecimals: true, //坐标轴刻度值是否允许为小数
	      title: { text: null },       
	      opposite:false,            
				plotLines:[{
					color: '#FF0000',
	        width: 2,
	        dashStyle:'dot',	       
	        value: yesterdayPrice               
			  }],
				tickPositioner:function(){//以yesterdayClose为界限，统一间隔值，从 最小到最大逼近
					positions=[],
					tick=avg_pxyAxisMin,
					increment=(avg_pxyAxisMax - avg_pxyAxisMin ) / 5;
					var tickMin=avg_pxyAxisMin,
						tickMax=avg_pxyAxisMax;
								
					if(items.length==0){//还没有数据时，yesterdayClose 的幅值 在 -1% - 1%上下浮动
				        tickMin=0.99*yesterdayPrice;
	                    tickMax=1.01*yesterdayPrice;
					}else if(increment==0){//有数据了  但是数据都是一样的幅值
						if(yesterdayPrice> avg_pxyAxisMin){
							tickMin=avg_pxyAxisMin;
							tickMax=2 * yesterdayPrice- avg_pxyAxisMin ;
						}else if(yesterdayPrice< avg_pxyAxisMin){
							tickMin=yesterdayPrice-(avg_pxyAxisMax-yesterdayPrice);
							tickMax=avg_pxyAxisMax;
						}else{
							tickMin=0.99 * yesterdayPrice;
							tickMax=1.01 * yesterdayPrice;
						}
					}else if(avg_pxyAxisMin-yesterdayPrice<0 && avg_pxyAxisMax-yesterdayPrice>0){//最小值在昨日收盘价下面，最大值在昨日收盘价上面
						var limit=Math.max(Math.abs(avg_pxyAxisMin-yesterdayPrice),Math.abs(avg_pxyAxisMax-yesterdayPrice));
							tickMin=yesterdayPrice-limit;
							tickMax=yesterdayPrice+limit;
						}else if(avg_pxyAxisMin>yesterdayPrice&& avg_pxyAxisMax>yesterdayPrice){//最小最大值均在昨日收盘价上面
							tickMin=yesterdayPrice-(tickMax-yesterdayPrice);
							tickMax=avg_pxyAxisMax;
						}else if(avg_pxyAxisMin<yesterdayPrice&& avg_pxyAxisMax<yesterdayPrice){//最小最大值均在昨日收盘价下面
							tickMin=avg_pxyAxisMin;
							tickMax=yesterdayPrice+(yesterdayPrice-tickMin);
						}
						if(tickMax > 2*yesterdayPrice){//数据超过100%了
							tickMin=0;
							tickMax=2 * yesterdayPrice;
						}
						var interval=(tickMax-yesterdayPrice)/10;
						tickMax+=interval;
						tickMin=yesterdayPrice-(tickMax-yesterdayPrice);
						increment=(tickMax-yesterdayPrice)/2;
						tick=tickMin;
						var i=0;
						for(tick;i++<5;tick+=increment){						
							positions.push(tick.toFixed(2));						
						}
							return positions;
				},
	       labels: {
//	         align: "right", //轴标签的水平对其方式
	           y:4,//标签偏移量
	           x:0,
	           enabled: true,
	           userHTML: true,
	           gridLineColor: "#f6f6f6",
	           style:{
	           	fontSize:fSize
	           },
	           formatter:function(e){
	           	 var flag;
	           	 if(this.value>yesterdayPrice){
	           	 	  flag='<span style="color:red;">'+this.value+'</span>'
	           	 }else{
	           	 	  flag='<span style="color:green;">'+this.value+'</span>'
	           	 }
	           	 if(this.value==yesterdayPrice){
	           	 		flag='<span style="color:black;">'+this.value+'</span>'
	           	 }
	           	 return flag;
	           }
	       },
	       crosshair:{
	           label:{
	               enabled: true,
	               formatter:function(e){
	                   return Highcharts.numberFormat(e,2);
	               },
	               padding:2,	              
//	               borderWidth:1,
	               backgroundColor:"black",
	               style:{
	               	"color":"white",
	               	"fontSize":'10px'
	               	}
	           }
	       },
	       showLastLabel: true, //是否显示最后一个轴标签
	       lineColor: "#f00"
	//     tickPixelInterval: 50 //如果刻度间隔为null，这个选项可以给刻度线设置一个大致的像素间隔值。不适用于分类轴。默认Y轴为72, X轴为100。
	      },
	      {
	      	showLastLabel: true, //是否显示最后一个轴标签
	        lineColor: "#f00",
	        labels: {
	//            align: "right", //轴标签的水平对其方式
	              y:4,
	              enabled: true,
	              userHTML: true,
	              gridLineColor: "#f6f6f6",
	              formatter:function(){//最新价  px_last/preclose昨收盘-1
	              	 var flag;
	              	 var num=(100*(this.value/yesterdayPrice-1)).toFixed(2);
	              	 if(num>0){
	              	 	 flag='<span style="color:red;">'+num+'%</span>'
	              	 }else{
	              	   flag='<span style="color:green;">'+num+'%</span>'
	              	 }
	              	 if(num==0){
	              	 	 flag='<span style="color:black;">'+num+'%</span>'
	              	 }
	              	 return flag;
//	               return (100*(this.value/yesterdayPrice-1)).toFixed(2)+"%";
	              },
	              style:{
			           	fontSize:fSize
			          }
	        },
	        opposite:true,
	      	tickPositioner:function(){							
					return positions;
				},
				crosshair:{
	              label:{
	                  enabled: true,
	                  padding:8,
	                  formatter:function(e){
	                      return Highcharts.numberFormat(e,2);
	                  },
	                  borderWidth:1,
	                  backgroundColor:"balck",
	                  style:{"color":"black",'backgroundColor':'balck'}
	              }
	         }
	      }];
	      //设置X轴	      
//	      options.xAxis.max=24;
//	      options.xAxis.tickInterval=60 * 1000 * 60 * 4;
	      options.xAxis.labels={	
	          	step:2,//显示间隔								
	              formatter: function () {
	              	var flag;console.log("typeVal："+typeVal);
	                if(typeVal==1){
	                	flag=Highcharts.dateFormat("%H:%M", this.value);
	                }else{
	                	flag=Highcharts.dateFormat("%m-%d", this.value);
	                }
	              	return flag;
	              },
	              style:{
	              	fontSize:fSize
	              }
	      };
	      options.xAxis.crosshair={
              label:{
                  enabled: true,
                  padding:8,
                  formatter:function(e){
                      return  Highcharts.dateFormat("%H:%M", e);
                  },
                  borderWidth:1,
                  backgroundColor:"black",
                  style:{"color":"white"}
              }
        };
    
			//设置series
			options.series=[			
			{
				  type: "areaspline",
			      name: "当前价",
			      enabledCrosshairs: true,
			      data:items,          
			      id:"area1",
			      color:'rgba(124, 181, 236, 0.3)',
			      lineColor:'#657FFB',
			      lineWidth:0.6
			},
			{
				type: "spline",
			      name: "平均走势线",
			      enabledCrosshairs: false,
			      data:calAvg(items),          
			      id:"avg_line",
			      color:'rgba(124, 181, 236, 0.3)',
			      lineColor:'orange',
			      lineWidth:0.6
			}];
			
			//执行画图
			myChart=Highcharts.StockChart(options);	   
			document.getElementById("loading").style.display="none";

});
}

//===K线图=======================
function kline(typeVal){

AJAX('/Quotation/GetCandlestick',{
	Code:GetQueryString("Code"), //产品代码
	QuotationType:typeVal //分时线类型
},function(data){   
   $.getJSON(data.entity,function(result){
    	if(typeVal==8){
    		items=result.reverse();
    	}else{
    		items=result.sort();
    	}   	
      
    	console.log(items);
    initOption();
   	options.tooltip.formatter=function(){	
		var e, t, o = this;
			return $.each(this.points, function () {
				var n = this.point.index;
//				    e = Highcharts.dateFormat("20%y-%m-%d %H:%M", this.x),
				    t =" 开:"+Highcharts.numberFormat(this.point.open,2)+
				    	 " 高:"+Highcharts.numberFormat(this.point.high,2)+
				    	 " 低:"+Highcharts.numberFormat(this.point.low,2)+
				    	 " 收:"+ Highcharts.numberFormat(this.point.close,2);			  
				}),
//				"当前时间："+e + "  " + 
				t +
				'<span style="color:#7cb5ec">&nbsp;MA5:'+this.points[0].point.y.toFixed(2) +'</span>'+
				'<span style="color:#434348">&nbsp;MA10:'+this.points[1].point.y.toFixed(2) +'</span>'+
				'<span style="color:#90ed7d">&nbsp;MA20:'+this.points[2].point.y.toFixed(2) +'</span>'
	};
	//设置X轴
//	options.xAxis.tickInterval=60 * 1000 * 60 * 24 * 30 * 1;
	options.xAxis.tickInterval= (function(){
		var flag ;
		switch(typeVal){
			case '8': 
			case '9': flag=60 * 1000 * 60 * 24 * 30 * 1;break; //间隔1个月
			case '10':flag=60 * 1000 * 60 * 24 * 30 * 12;break; //间隔1个月
			case '3': flag=60 * 1000 * 15 ;break; //间隔15分钟
			case '4': flag=60 * 1000 * 75 ;break; //间隔75分钟
			case '5': flag=60 * 1000 * 60 * 8 ;break; //间隔8小时
			case '6': flag=60 * 1000 * 60 * 24 * 1 ; break; //间隔1天
			case '7': falg=60 * 1000 * 60 * 24 * 1 ;break; //间隔1天
		}
		return flag; 
		
	})();

	options.xAxis.labels={
//		step:3,
		formatter:function(){	
			if(typeVal>7){
				return Highcharts.dateFormat("%Y-%m", this.value);
			}else{
				return Highcharts.dateFormat("%m-%d %H:%M", this.value);
			}
//			var flag;console.log(typeVal);
//			switch(typeVal){
//				case '8':
//				case '9': 
//				case '10':return Highcharts.dateFormat("%Y-%m", this.value);break; //间隔一年
//				case '3':
//				case '4': 
//				case '5': 
//				case '6': 
//				case '7':return Highcharts.dateFormat("%H:%M", this.value);break;
//			}
//			return Highcharts.dateFormat("%Y-%m", this.value);
		},
		style:{
			fontSize:fSize
		}
	};
	options.xAxis.crosshair={
    label:{
        enabled: true,
        padding:8,
        formatter:function(e){
            return  Highcharts.dateFormat("%Y-%m-%d %H:%M", e);
        },
        borderWidth:1,
        backgroundColor:"black",
        style:{"color":"white"}
    }
};

	options.navigator.enabled=true;
//	options.scrollbar.enabled=true;
	options.rangeSelector.selected=(function(){
		var selNum;
		switch(typeVal){
			case '8': 
			case '9': selNum=0;break;
			case '10':selNum=1;break;
			case '3': 
			case '4': 
			case '5': 
			case '6': 
			case '7': selNum=(typeVal-1);break;
		}
		return selNum;
	})();
	
	//设置Y轴
	options.yAxis=[{
		allowDecimals: true, //坐标轴刻度值是否允许为小数
	    title: { text: null },       
	    opposite:false,	
		labels: {
		    y:4,//标签偏移量
		    x:0,
//		  step:5,
			style:{
				fontSize:fSize
			},
	        enabled: true,
	        userHTML: true,
	        gridLineColor: "#f6f6f6"        
       
    	},
    crosshair:{
//  	snap:false,  //自动靠近功能
      label:{      	  
          enabled: true,
          padding:8,
          formatter:function(e){
           return Highcharts.numberFormat(e, 2);
          },
      	borderWidth:1,
          	backgroundColor:"balck",
          	style:{"color":"white"}
      	}
      },
    showLastLabel: true, //是否显示最后一个轴标签
    lineColor: "#f00"
		
	}];
	//设置series
	options.series=[
	{
		type:'spline',
		name:'MA5',
		enabledCrosshairs: false,
		data:calculateMA(5,items),
	  id:"m5"	 
	},{
		type:'spline',
		name:'MA10',
		enabledCrosshairs: false,
		data:calculateMA(10,items),
	  id:"m10"
	},{
		type:'spline',
		name:'MA20',
		enabledCrosshairs: false,
		data:calculateMA(20,items),
	  id:"m20"
	},
	{
		type: "candlestick",
	  name: "当前价",
	  enabledCrosshairs: true,	 
	  data:items, 
	  id:"k1"
	 
	}
	];		
	//执行画图
	myChart=Highcharts.StockChart(options);
	document.getElementById("loading").style.display="none";
	   });
 });

}
